package com.doge.walknovel

import android.app.Application
import android.content.IntentFilter
import android.os.Process.setThreadPriority
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.doge.walknovel.analysis.AppsFlyerHelper
import com.doge.walknovel.analysis.analysisInitUser
import com.doge.walknovel.api.workThreadPool
import com.doge.walknovel.business.home.discover.DiscoverRepository
import com.doge.walknovel.business.reader.menus.ReaderHelper
import com.doge.walknovel.core.account.AppUserViewModel
import com.doge.walknovel.push.FCMService
import com.doge.walknovel.push.PushHelper
import com.doge.walknovel.push.PushReceiver
import com.doge.walknovel.utils.*
import com.doge.wnpro.BuildConfig
import com.facebook.FacebookSdk
import com.facebook.appevents.AppEventsLogger
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.hjq.permissions.XXPermissions
import com.tendcloud.tenddata.TCAgent
import kotlin.system.exitProcess
import com.doge.wnpro.R

class App : Application(), ViewModelStoreOwner {
    private val appViewModelStore by lazy { ViewModelStore() }
    private val appViewModelFactory by lazy {
        ViewModelProvider.AndroidViewModelFactory.getInstance(
            this
        )
    }

    override fun onCreate() {
        context = this
        super.onCreate()
        log("App onCreate")
        XXPermissions.setScopedStorage(true) // 0ms
        FacebookSdk.sdkInitialize(this)  // 0ms
        Thread.setDefaultUncaughtExceptionHandler { _, e ->
            e.printStackTrace()
            Activities.finishAll()
            TCAgent.onError(appContext, e)
            FirebaseCrashlytics.getInstance().recordException(e)
            android.os.Process.killProcess(android.os.Process.myPid())
            exitProcess(0)
        }  // 0ms

        Thread {
            setThreadPriority(android.os.Process.myTid(), android.os.Process.THREAD_PRIORITY_BACKGROUND)
            systemWindowInsetsTop.postValue(statusBarHeight)
            registerReceiver(PushReceiver(), IntentFilter(FCMService.FIREBASE_MESSAGE))   // 30ms
            AppEventsLogger.activateApp(this)  // facebook // 10ms
            TCAgent.init(this, getString(R.string.td_app_id), BuildConfig.CHANNEL)  // 110ms
            TCAgent.setReportUncaughtExceptions(true)  // 0ms
            FirebaseAnalytics.getInstance(appContext).setAnalyticsCollectionEnabled(true)
            ReaderHelper.initialized() // 20ms
            OAIDUtils.initialized()
            AppsFlyerHelper.initialized()   // 60ms

            ioThreadPool.toString() // init ioThreadPool
            workThreadPool.toString() // init workThreadPool
            analysisInitUser()  // 30ms
            // data preload
            PushHelper.check()
            AppUserViewModel.get().requestSelfInfo()
            DiscoverRepository.get().request(justCache = true)
            log("App onCreate async init completed")
        }.start()
    }

    fun getAppViewModelProvider() = ViewModelProvider(this, appViewModelFactory)
    override fun getViewModelStore() = appViewModelStore

    companion object {
        lateinit var context: Application
    }
}